package com.wx.activitys.drp.controller;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.github.sd4324530.fastweixin.api.JsAPI;
import com.github.sd4324530.fastweixin.api.response.GetSignatureResponse;
import com.github.sd4324530.fastweixin.api.response.GetUserInfoResponse;
import com.wx.activitys.base.utils.Common;
import com.wx.activitys.base.utils.WebUtil;
import com.wx.activitys.drp.JsonResult;
import com.wx.activitys.drp.EnumUtils.GradeState;
import com.wx.activitys.drp.EnumUtils.WithdrawStateType;
import com.wx.activitys.drp.Utils.DoubleUtil;
import com.wx.activitys.drp.barcode.ImageMarkLogoByIcon;
import com.wx.activitys.drp.barcode.QRCodeUtil;
import com.wx.activitys.drp.model.BCard;
import com.wx.activitys.drp.model.BClick;
import com.wx.activitys.drp.model.BGrade;
import com.wx.activitys.drp.model.BUserIncome;
import com.wx.activitys.drp.model.BUserInfo;
import com.wx.activitys.drp.model.BWithdrawal;
import com.wx.activitys.drp.service.BCardService;
import com.wx.activitys.drp.service.BClickService;
import com.wx.activitys.drp.service.BGradeService;
import com.wx.activitys.drp.service.BUserIncomeService;
import com.wx.activitys.drp.service.BWithdrawalService;
import com.wx.activitys.drp.service.UserInfoService;
import com.wx.activitys.xmlInterf.aipg.singleacctvalid.ValidR;
import com.wx.activitys.xmlInterf.allinpay.xmltrans.demo.TranxMain;

import sun.misc.BASE64Decoder;

@Controller
@RequestMapping("/member")
public class MemberController {
	@Autowired
	private UserInfoService userInfoService;

	@Autowired
	private BCardService bCardService;

	@Autowired
	private BWithdrawalService bWithdrawalService;

	@Autowired
	private BUserIncomeService bUserIncomeService;
	
	@Autowired
	private BClickService bClickService;
	
	@Autowired
	private JsAPI jsAPI;
	
	@Autowired
	private BGradeService bGradeService;
	

	@RequestMapping(method = { RequestMethod.GET }, value = "/add.html")
	public String add() {
		return "drp/register";
	}

	/**
	 * 会员中心
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "memberCenter.html", method = RequestMethod.GET)
	public String memberCenter(Model model, HttpServletRequest request) {
		GetUserInfoResponse userInfo = ((GetUserInfoResponse) request.getSession().getAttribute("userInfo"));
		if (userInfo!=null) {
			String openid=userInfo.getOpenid();
			//String openid="oCdHJw6bk1jzMU_WWcDe90NTZERg";
			BUserInfo buserInfo = userInfoService.findByOpenid(openid);
			if (StringUtils.isNotBlank(buserInfo.getAuthInfo())) {
				JSONObject jsStr = JSONObject.parseObject(buserInfo.getAuthInfo());
				model.addAttribute("authInfo", jsStr);
			}
			model.addAttribute("buserInfo", buserInfo);
			return "drp/user/user";
		} else {
			return "error/error";
		}

	}

	/**
	 * 添加银行卡跳转
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "addCard.html", method = RequestMethod.GET)
	public String addcard(Model model, HttpServletRequest request) {
	 GetUserInfoResponse userInfo =((GetUserInfoResponse)request.getSession().getAttribute("userInfo"));
		if(userInfo!=null){
			String openid= userInfo.getOpenid();
			//String openid= "oCdHJw6bk1jzMU_WWcDe90NTZERg";
			BUserInfo entity = userInfoService.findByOpenid(openid);
			model.addAttribute("bUserInfo", entity);
			return "drp/user/add-card";
		}else{
	       return "error/error";
		}
		
		
	}
	
	
	/**
	 * 添加银行卡
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "addBank.html", method = RequestMethod.POST)
	@ResponseBody
	public JsonResult addcard1(Model model, HttpServletRequest request) {
		String bankName=  request.getParameter("bankName");
		String bankcardId = request.getParameter("bankcardId");
		String bankCode = request.getParameter("bankCode");
		String phone=request.getParameter("phone");
		BCard bd = bCardService.listCardByCardId(bankcardId);
		if(bd!=null){
			return JsonResult.fail("不能重复绑定",bd);
		}
		GetUserInfoResponse userInfo =((GetUserInfoResponse)request.getSession().getAttribute("userInfo"));
		String openid=userInfo.getOpenid();
		//String  openid= "oCdHJw6bk1jzMU_WWcDe90NTZERg";
		BUserInfo entity = userInfoService.findByOpenid(openid);
		ValidR var = new ValidR();
		var.setBANK_CODE(bankCode);
		var.setACCOUNT_NO(bankcardId);
		var.setACCOUNT_NAME(entity.getName());
		var.setID(entity.getIdNumber());
		var.setTEL(phone);
		TranxMain tr = new TranxMain();
		String result= tr.idVerify(var);
		if(result==""){
			return JsonResult.fail("处理失败,请重新提交","");	
		}else{ 
			String msg =result.substring(0,(result.indexOf("-")));
			String code = result.substring(result.indexOf("-")+1);
			if(code.equals("0000")){
				BCard bCard = new BCard();
				bCard.setCardId(bankcardId);
				bCard.setOpenid(openid);
				bCard.setSource(bankName);
				bCard.setCode(bankCode);
				bCard.setCreateTime(new Date());
				bCard.setState(1);
				int flag = bCardService.insertCard(bCard);
				if(flag>0){
				  return JsonResult.success("操作成功",flag);
				}
				return JsonResult.fail("操作失败","");
			}else{
				return JsonResult.fail(msg,"");
			}
		}
		
	}

	/**
	 * 推广分享
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	String BASE_PATH = "http://jh.xuanzhen-tech.com";
	@RequestMapping(value = "share.html", method = RequestMethod.GET)
	public String share(Model model, HttpServletRequest request) {
		GetUserInfoResponse userInfo = ((GetUserInfoResponse) request.getSession().getAttribute("userInfo"));
		String currentPage = BASE_PATH + "/member/share.html";
		GetSignatureResponse signObj = jsAPI.getSignature(currentPage);
		model.addAttribute("signObj", signObj);
		model.addAttribute("basePath", BASE_PATH);
		if (userInfo != null) {
			BUserInfo bUserInfo = userInfoService.findByOpenid(userInfo.getOpenid());
			if (StringUtils.isBlank(bUserInfo.getCodeImgUrl())) {
				String text = "http://jh.xuanzhen-tech.com/enter/auth2.html?onOpenId="+userInfo.getOpenid();
				String codeV = "";
				String srcImgPath = Common.IMG_SAVE_BASEPATH + "tui2.jpg";
				String code = "";
				Map<String, Object> map = new HashMap<>();
				try {
					String path = Common.IMG_SAVE_BASEPATH + "qrcode/";
					String imgUrl=bUserInfo.getHeadImgUrl();
					//String strUrl="http://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTLlk8ibibibyz8RAFuqu1h6Hiawd3icSKqzV1KfibtGhCfuic8sqIWFKvhDWdtApK88hmWIEibMRnNGFjsyhg/0";
					//读取微信图片保存到本地
					QRCodeUtil.writeFile(path, imgUrl);
					// 生成二维码
					codeV = QRCodeUtil.encode(text,path+"head.jpg",path);
					// 给图片添加水印
					String iconPath = path + codeV;
					code = ImageMarkLogoByIcon.markImageByIcon(iconPath, srcImgPath, path);
					map.put("openid", bUserInfo.getOpenid());
					map.put("codeImgUrl", "qrcode/" + code);
					userInfoService.update(map);
					model.addAttribute("url", "qrcode/"+code);
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				model.addAttribute("url", bUserInfo.getCodeImgUrl());
			}
			return "drp/user/share";
		} else {
			return "error/error";
		}
	}

	/**
	 * 银行卡管理
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "bankCard.html", method = RequestMethod.GET)
	public String card(Model model, HttpServletRequest request) {
	GetUserInfoResponse userInfo = ((GetUserInfoResponse) request.getSession().getAttribute("userInfo"));
		if(userInfo!=null){
			String openid=userInfo.getOpenid();
			//String openid="oCdHJw6bk1jzMU_WWcDe90NTZERg";
			List<BCard> bCards = bCardService.listCardByOpenid(openid);
			BUserInfo buserInfo = userInfoService.findByOpenid(openid);
			for (BCard bCard : bCards) {
				String cardId = bCard.getCardId();
				String cardIdShow = cardId.substring(cardId.length() - 4);
				bCard.setCardIdCopy(cardIdShow);
			}
			model.addAttribute("bCards", bCards);
			model.addAttribute("buserInfo", buserInfo);
			return "drp/user/bank-card";
		
		}else{ 
			return "error/error"; 
		}
	}

	/**
	 * 银行卡删除
	 * 
	 * @param bWithdrawal
	 * @return
	 */
	@RequestMapping(value = "deleteCard.html", method = RequestMethod.POST)
	@ResponseBody
	public JsonResult deleteCard(HttpServletRequest request, @RequestParam String cardId) {
		GetUserInfoResponse userInfo = ((GetUserInfoResponse) request.getSession().getAttribute("userInfo"));
		Map<String, Object> param = new HashMap<>();
		if(userInfo!=null){
		param.put("cardId", cardId);
		param.put("state", 0);
		int flag = bCardService.deleteBycardId(param);
		if (flag > 0) {
			return JsonResult.success("删除成功", flag);
		}
		return JsonResult.fail("删除失败，请重新申请", "");
		
		} 
		return JsonResult.fail("删除失败，请重新申请", "");
	}

	/**
	 * 现金提现跳转
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "cashPresent.html", method = RequestMethod.GET)
	public String cash(Model model, HttpServletRequest request) {
		SimpleDateFormat sdfMonth = new SimpleDateFormat("yyyy-MM");
		SimpleDateFormat sdfDay = new SimpleDateFormat("yyyy-MM-dd");
		GetUserInfoResponse userInfo = ((GetUserInfoResponse) request.getSession().getAttribute("userInfo"));
		if(userInfo!=null){
			String openid = userInfo.getOpenid();
			//String openid = "oCdHJw6bk1jzMU_WWcDe90NTZERg";
			List<BCard> bCards = bCardService.listCardByOpenid(openid);
			BUserInfo buserInfo = userInfoService.findByOpenid(openid);
			Map<String,Object> map = new HashMap<>();
			map.put("openid",openid);
			map.put("createTime",sdfMonth.format(new Date()));
			int monthCount=bWithdrawalService.countByMap(map);
			map.put("createTime", sdfDay.format(new Date()));
			int dayCount=bWithdrawalService.countByMap(map); 
			for (BCard bCard : bCards) {
				String cardId = bCard.getCardId();
				String cardIdShow = cardId.substring(0, 4) + " **** **** ****" + cardId.substring(cardId.length() - 3);
				bCard.setCardIdCopy(cardIdShow);
			}
			model.addAttribute("monthCount", monthCount);
			model.addAttribute("dayCount", dayCount);
			model.addAttribute("bCards", bCards);
			model.addAttribute("buserInfo", buserInfo);
			return "drp/user/cash-present";
		}else{ 
			return "error/error"; 
		}
	}

	/**
	 * 现金提现
	 * 
	 * @param bWithdrawal
	 * @return
	 */
	@RequestMapping(value = "insertCash.html", method = RequestMethod.POST)
	@ResponseBody
	public JsonResult insertCash(BWithdrawal bWithdrawal, HttpServletRequest request) {
		int monthCount=WebUtil.getInt(request, "monthCount", 1);
		GetUserInfoResponse userInfo = ((GetUserInfoResponse) request.getSession().getAttribute("userInfo"));
		if(userInfo!=null){
		BUserInfo buserInfo = userInfoService.findByOpenid(bWithdrawal.getOpenid());
		Double sub = DoubleUtil.sub(buserInfo.getIncome(), bWithdrawal.getNumber());
		if (sub < 0) {
			return JsonResult.fail("申请失败，请重新申请", "");
		}
		if(monthCount>=5){
			bWithdrawal.setNumber(DoubleUtil.sub(bWithdrawal.getNumber(),2.0));
		}
		bWithdrawal.setCreateTime(new Date());
		bWithdrawal.setState(WithdrawStateType.处理中.getValue());
		int flag = bWithdrawalService.insertWithdrawal(bWithdrawal,sub);
		if (flag > 0) {
			return JsonResult.success("申请成功", flag);
		}
		return JsonResult.fail("申请失败，请重新申请", flag);
		
		} 
		return JsonResult.fail("申请失败，请重新申请", "");
	}
	
	
	/**
	 * 
	 * 等级申请
	 * @param bWithdrawal
	 * @return
	 */
	@RequestMapping(value = "insertGrade.html", method = RequestMethod.POST)
	@ResponseBody
	public JsonResult insertGrade(HttpServletRequest request) {
		GetUserInfoResponse userInfo = ((GetUserInfoResponse) request.getSession().getAttribute("userInfo"));
		if(userInfo!=null){
		 String openid = userInfo.getOpenid();
		 //String openid = "oCdHJw1cBpl_zaLH-qdSHrvoA2Cw";
		 BGrade entity = new BGrade();
		 entity.setOpenid(openid);
		 entity.setState(GradeState.待审核.getValue());
			List<BGrade> list = bGradeService.selectByEntity(entity);
			if(list.size()>0){
				return JsonResult.success("申请待审核中，不能重复申请", "");
			}
	        entity.setCreateTime(new Date());
	        entity.setId(Common.generateUUID());;
			int flag = bGradeService.insert(entity);
		if (flag > 0) {
			return JsonResult.success("申请已提交", flag);
		}
		return JsonResult.success("申请失败，请重新申请", flag);
		} 
		return JsonResult.success("申请失败，请重新申请", "");
	}

	/**
	 * 用户信息
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "memberMessage.html", method = RequestMethod.GET)
	public String memberMessage(Model model, HttpServletRequest request) {
		GetUserInfoResponse userInfo = ((GetUserInfoResponse) request.getSession().getAttribute("userInfo"));
		if (userInfo != null) {
			BUserInfo buserInfo = userInfoService.findByOpenid(userInfo.getOpenid());
			model.addAttribute("buserInfo", buserInfo);
			return "drp/personMessage";
		} else {
			return "error/error";
		}
	}

	/**
	 * 企业身份认证跳转
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "enterprise.html", method = RequestMethod.GET)
	public String identity(Model model, HttpServletRequest request) {
		GetUserInfoResponse userInfo = ((GetUserInfoResponse) request.getSession().getAttribute("userInfo"));
		if (userInfo != null) {
			return "drp/identity/identityCompany";
		} else {
			return "error/error";
		}
	}

	/**
	 * 个人身份认证跳转
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "personEnterprise.html", method = RequestMethod.GET)
	public String identity1(Model model, HttpServletRequest request) {
		GetUserInfoResponse userInfo = ((GetUserInfoResponse) request.getSession().getAttribute("userInfo"));
		if (userInfo != null) {
			return "drp/identity/identityPersonal";
		} else {
			return "error/error";
		}
	}

	/**
	 * 身份认证（包括企业与个人）
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "updateAuthInfo.html", method = RequestMethod.POST)
	@ResponseBody
	public JsonResult updateAuthInfo(Model model, HttpServletRequest request, @RequestParam Map<String, Object> map) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String path = Common.IMG_SAVE_BASEPATH + "identity/";
		// 认证信息，json字符串存放在数据库
		SerializerFeature[] features = new SerializerFeature[6];
		features[0] = SerializerFeature.WriteMapNullValue;
		features[1] = SerializerFeature.WriteNullListAsEmpty;
		features[2] = SerializerFeature.DisableCircularReferenceDetect;
		features[3] = SerializerFeature.WriteDateUseDateFormat;
		features[4] = SerializerFeature.WriteNullNumberAsZero;
		features[5] = SerializerFeature.WriteNullStringAsEmpty;
	GetUserInfoResponse userInfo = ((GetUserInfoResponse) request.getSession().getAttribute("userInfo"));
		if (StringUtils.isNotBlank(userInfo.getOpenid())) {
	        //String openid= "oCdHJw6bk1jzMU_WWcDe90NTZERg";
			String openid= userInfo.getOpenid();
			String authenticationType = (String) map.get("type");
			if (authenticationType.equals("个人")) {
				String imgStr = (String) map.get("idCard");
				String ingPath = GenerateImage(imgStr, path);
				map.put("idCard", ingPath);
			}
			if (authenticationType.equals("企业")) {
				String imgStr1 = (String) map.get("idCard");
				String imgStr2 = (String) map.get("licenseAttachment");
				String ingPath1 = GenerateImage(imgStr1, path);
				String ingPath2 = GenerateImage(imgStr2, path);
				map.put("idCard", ingPath1);
				map.put("licenseAttachment", ingPath2);
			}
			String str = JSONObject.toJSONString(map, features);
			int flag = 0;
			map.clear();
			Map<String, Object> paramMap = new HashMap<>();
			paramMap.put("openid",openid);
			paramMap.put("authInfo", str);
			paramMap.put("authenticationType", authenticationType);
			paramMap.put("applyTime", sdf.format(new Date()));
			paramMap.put("attestationStatus",1);
			flag = userInfoService.update(paramMap);
			if (flag > 0) {
				return JsonResult.success("提交成功", flag);
			} else {
				return JsonResult.fail("提交失败", flag);
			}

		} else {
			return JsonResult.success("提交失败", "");
		}

	}

	/**
	 * 修改密码跳转
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "updatePassword.html", method = RequestMethod.GET)
	public String updatePassword(Model model, HttpServletRequest request) {
		String phone = request.getParameter("phone");
		model.addAttribute("phone", phone);
		return "drp/password";
	}

	/**
	 * 修改密码
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "updatePwd.html", method = RequestMethod.POST)
	@ResponseBody
	public JsonResult updatePwd(Model model, HttpServletRequest request) {
		GetUserInfoResponse userInfo = ((GetUserInfoResponse) request.getSession().getAttribute("userInfo"));
		String password = request.getParameter("password");
		Map<String, Object> map = new HashMap<>();
		if (userInfo != null) {
			int flag = 0;
			map.put("openid", userInfo.getOpenid());
			map.put("password", password);
			flag = userInfoService.update(map);
			if (flag > 0) {
				return JsonResult.success("密码修改成功", flag);
			} else {
				return JsonResult.success("密码修改失败", flag);
			}
		} else {
			return JsonResult.success("密码修改失败", "");
		}

	}

	/**
	 * 
	 * 收入统计
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "incomeStatistics.html", method = RequestMethod.GET)
	public String incomeStatistics(Model model, HttpServletRequest request) {
		/*GetUserInfoResponse userInfo = ((GetUserInfoResponse) request.getSession().getAttribute("userInfo"));
		if (userInfo != null) {*/
		    String openid = "oCdHJw6bk1jzMU_WWcDe90NTZERg";
		    //String openid =userInfo.getOpenid();
			String date = request.getParameter("date");
			Map<String, Object> param = new HashMap<>();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
			param.put("openid",openid);
			if (StringUtils.isNotBlank(date)) {
				try {
					param.put("createTime", sdf.format(sdf.parse(date)));
				} catch (ParseException e) {
					e.printStackTrace();
				}
				model.addAttribute("date", date);
			} else {
				Date date1 = new Date();
				param.put("createTime", sdf.format(date1));
				model.addAttribute("date", sdf.format(date1));
			}
			List<BWithdrawal> withLists = bWithdrawalService.findByEntity(param);
			List<BUserIncome> lists = bUserIncomeService.listDayIncomebyOpenid(param);
			double sum = 0.0;
			for (BUserIncome bUserIncome : lists) {
				sum += bUserIncome.getIncome();
			}
			model.addAttribute("withLists", withLists);
			model.addAttribute("bUserIncome", lists);
			model.addAttribute("sum", sum);
			return "drp/user/incomeStatistics";
			/*} else {
			return "error/error";
		}*/

	}

	/**
	 * 分销统计
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "statistics.html", method = RequestMethod.POST)
	@ResponseBody
	public JsonResult statistics(Model model, HttpServletRequest request) {
		GetUserInfoResponse userInfo = ((GetUserInfoResponse) request.getSession().getAttribute("userInfo"));
		String date = request.getParameter("date");
		Map<String, Object> param = new HashMap<>();
		List<BClick> lists = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		if (userInfo != null) {
			param.put("openid", userInfo.getOpenid());
			if (StringUtils.isBlank(date)) {
				Date date1 = new Date();
				param.put("createTime", sdf.format(date1));
			} else {
				try {
					param.put("createTime", sdf.format(sdf.parse(date)));
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
			lists = bClickService.findclickNumByOpenid(param);
			return JsonResult.success("查询成功", lists);

		} else {
			return JsonResult.success("查询失败", lists);
		}
	}

	public static String GenerateImage(String imgStr, String imgFilePath) {// 对字节数组字符串进行Base64解码并生成图片
		if (imgStr == null) // 图像数据为空
			return null;
		BASE64Decoder decoder = new BASE64Decoder();
		try {
			// Base64解码
			byte[] bytes = decoder.decodeBuffer(imgStr);
			for (int i = 0; i < bytes.length; ++i) {
				if (bytes[i] < 0) {// 调整异常数据
					bytes[i] += 256;
				}
			}
			//File file1 = new File(imgFilePath);
			//file1.mkdirs();
			String fileName = Common.generateUUID() + ".jpg";
			String file = imgFilePath + fileName;
			// 生成jpeg图片
			OutputStream out = new FileOutputStream(file);
			out.write(bytes);
			out.flush();
			out.close();
			return "identity/" + fileName;
		} catch (Exception e) {
			return null;
		}
	}

}
